package com.fdb.efp.nls.service.impl.yed.apply;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fdb.efp.nls.service.facade.NlsApplyInfoService;
import com.fdb.efp.nls.service.facade.queue.NlsProcessBizService;
import com.fdb.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.fdb.efp.nls.service.impl.yed.apply.bean.SignContractBean;
import com.fdb.efp.nls.service.impl.yed.apply.ctrcont.YedApplyCtrLoanCtr;
import com.fdb.efp.nls.service.vo.NlsApplyInfoVO;
import com.fdb.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.fdb.efp.nls.service.vo.sx.NlsCreditInfoVO;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.TimeType;
import com.fdb.basic.framework.core.exception.BizException;
import com.fdb.basic.framework.core.exception.OcmSystemException;
import com.fdb.basic.framework.core.util.DateUtility;
import com.fdb.basic.framework.core.util.MessageRuleCheckUtil;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.fdb.efp.basic.framework.mq.constant.TagEnums;
import com.fdb.efp.basic.framework.mq.constant.TopicEnums;
import com.fdb.efp.nls.common.ConsoleConstant;
import com.fdb.efp.nls.common.YedConstantSet;
import com.fdb.efp.nls.service.facade.SOrgService;
import com.fdb.efp.nls.service.vo.SOrgVO;
import com.fdb.efp.nls.service.facade.CtrLoanContService;
import com.fdb.efp.nls.service.vo.CtrLoanContVO;
import com.fdb.efp.cus.service.facade.CusIndivService;
import com.fdb.efp.cus.service.facade.CusReferrerInfoService;
import com.fdb.efp.cus.service.vo.CusIndivVO;
import com.fdb.efp.cus.service.vo.CusReferrerInfoVO;
import com.fdb.efp.nls.service.vo.CfcaSignInfoVO;
import com.fdb.efp.nls.service.vo.ImageBizDetailVO;
import com.fdb.efp.nls.service.vo.YedUploadRecordVO;
import com.fdb.efp.nls.service.facade.CfcaSignInfoService;
import com.fdb.efp.nls.service.facade.ImageBizDetailService;
import com.fdb.efp.nls.service.facade.signature.YedContResult;
import com.fdb.efp.nls.service.facade.signature.YedContService;
import com.fdb.efp.nls.service.facade.yed.YedUploadService;
import com.fdb.efp.esb.common.constant.ElectronicSignatureEnums;
import com.fdb.efp.limit.service.facade.LmtPrdContService;
import com.fdb.efp.limit.service.vo.LmtPrdContVO;
import com.fdb.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.fdb.efp.nls.service.impl.SoltServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.fdb.efp.esb.common.constant.ElectronicSignatureConstant.CONT_STATUS_200;
import static com.fdb.efp.nls.common.constant.yed.NlsApplyFlowStatus.FLOW_STATUS_4;

/**
 * 需求编号：优e贷需求编号<br/>
 * 问题编号：<br/>
 * 功能描述：优e贷合同签订插槽<br/>
 * 开发人员：zhangxican<br/>
 * 创建时间：2020年8月24日18:10:22
 *
 * @Author zhangxican
 * @Version 1.0
 * @Since 1.0
 */
@Service("yedSignContractService")
@Scope("prototype")
public class YedSignContractServiceImpl extends SoltServiceImpl implements Runnable {
    // 日志
    private static final Logger logger = LoggerFactory.getLogger(YedSignContractServiceImpl.class);

    private boolean Flag = false;

    private NlsApplyInfoVO nlsApplyInfoVO;

    public NlsApplyInfoVO getNlsApplyInfoVO() {
        return nlsApplyInfoVO;
    }

    public void setNlsApplyInfoVO(NlsApplyInfoVO nlsApplyInfoVO) {
        this.nlsApplyInfoVO = nlsApplyInfoVO;
    }

    @Override
    public void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
        //查询该笔用信对应的授信信息
        String applySeq = nlsApplyInfoVO.getApplySeq();
        boolean flag = false;
        String msg = "";
        try {
            logger.info("======>优e贷合同签订服务开始,流水号" + applySeq + "<======");
            /*logger.info("======>检查授信合同是否签订,流水号" + applySeq + "<======");
            YedUploadRecordVO recordVO = new YedUploadRecordVO();
            recordVO.setApplSeq(nlsApplyInfoVO.getLmtApplySeq());
            recordVO.setPrdId(YedConstantSet.prdId);
            recordVO.setFileType(YedConstantSet.IMAGE_TYPE_Y05);
            recordVO = yedUploadService.queryByCond(recordVO);
            if (recordVO == null ) {
                if (logger.isErrorEnabled()) {
                    logger.error("用信申请流水号为【" + nlsApplyInfoVO.getApplySeq() + "】未签订授信合同");
                    nlsApplyInfoVO.setNlsApplyState(BaseConstant.NLS_APPLY_STATE_03);//修改申请状态为失败
                    nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
                    throw new OcmSystemException("用信申请流水号为【" + nlsApplyInfoVO.getApplySeq() + "】未签订授信合同");

                }
            }*/

            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
            nlsCreditInfoVO = nlsCreditInfoService.queryByPk(nlsCreditInfoVO);
//            Optional.ofNullable(nlsCreditInfoVO).orElseThrow(() -> new OcmSystemException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "用信申请流水号为【" + nlsApplyInfoVO.getApplySeq() + "】不存在授信"));
            if (nlsCreditInfoVO == null ) {
                if (logger.isErrorEnabled()) {
                    logger.error("用信申请流水号为" + applySeq + "不存在授信");
                    flag = true;
                    msg = "不存在授信";
                    throw new OcmSystemException("用信申请流水号为" + applySeq + "不存在授信");
                }
            }

            JSONObject signContractJson = (JSONObject) nlsApplyInfoVO.getSignContractBean();
            SignContractBean signContractBean = new SignContractBean();

            CusIndivVO cusIndivVO = null;
            CfcaSignInfoVO cfcaSignInfoVO = null;
            if (Objects.isNull(signContractJson)) {
                //获取客户信息
                CusIndivVO cusIndivVO1 = new CusIndivVO();
                cusIndivVO1.setCusId(nlsCreditInfoVO.getCusId());
                cusIndivVO = cusIndivService.queryByPk(cusIndivVO1);
                //cusIndivVO = signContractBean.getCusIndivVO(cusIndivService, cusIndivVO);
                // 获取合同签订信息
                CfcaSignInfoVO cfcaSignInfoVO1 = new CfcaSignInfoVO();
                cfcaSignInfoVO1.setApplySeq(applySeq);
                cfcaSignInfoVO = cfcaSignInfoService.queryByPk(cfcaSignInfoVO1);
                //cfcaSignInfoVO = signContractBean.getCfcaSignInfoVO(cfcaSignInfoService, cfcaSignInfoVO);
            } else {
                cusIndivVO = signContractJson.getObject("cusIndivVO", CusIndivVO.class);
                cfcaSignInfoVO = signContractJson.getObject("cfcaSignInfoVO", CfcaSignInfoVO.class);
                signContractBean.setCusIndivVO(cusIndivVO);
                signContractBean.setCfcaSignInfoVO(cfcaSignInfoVO);
                nlsApplyInfoVO.setSignContractBean(signContractBean);
            }

            if (cusIndivVO == null ) {
                if (logger.isErrorEnabled()) {
                    logger.error("优e贷合同签订服务 用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】通过【" + nlsApplyInfoVO.getCusId() + "】查询客户信息为空 或 安心签用户号为空 请核查!!!");
                    flag = true;
                    msg ="查询客户信息为空 或 安心签用户号为空!";
                    throw new OcmSystemException("优e贷合同签订服务 用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】通过【" + nlsApplyInfoVO.getCusId() + "】查询客户信息为空 或 安心签用户号为空  请核查!!!");
                }
            }
            String axquserid = cusIndivVO.getAxqUsrId();
            YedContResult yedContResult1=null;
            if(StringUtils.isEmpty(axquserid)){
                try {
                    yedContResult1  = yedContService.openAccount(cusIndivVO.getCusName(),cusIndivVO.getCertType(),cusIndivVO.getCertCode(),cusIndivVO.getEmail(),cusIndivVO.getPhone(),cusIndivVO.getIndivRsdAddr(),nlsApplyInfoVO.getLmtApplySeq());
                    axquserid = Objects.requireNonNull(yedContResult1).getAxqUserId();
                }catch (Exception e){
                    logger.error("安心签开户异常，用信流水号"+nlsApplyInfoVO.getApplySeq()+"-错误信息为"+yedContResult1.getMsg());
                    flag = true;
                    msg = "安心签开户异常";
                    throw new OcmSystemException(yedContResult1.getMsg());
                }
                if (!yedContResult1.isRetFlag()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("【优e贷合同签订服务】用信申请流水号：" + applySeq + " 安心签开户出现异常，异常信息为" + yedContResult1.getMsg());
                        flag = true;
                        msg = "安心签开户出现异常";
                    }
                    throw new OcmSystemException(yedContResult1.getMsg());
                }
            }


            // 调3203合同签订 todo 失败重签3次，仍失败，记录失败信息
            if (Objects.isNull(cfcaSignInfoVO)) {
                SOrgVO sOrgVO = null;
                try {
                    sOrgVO = getSOrg(nlsCreditInfoVO.getNlsOperOrgid());
                }catch(Exception e){
                    logger.error("获取到机构信息为空！用信流水号为"+nlsApplyInfoVO.getApplySeq());
                    flag = true;
                    msg = "获取到机构信息为空";
                    throw new OcmSystemException("获取到机构信息为空！");
                }
                Map<String, String> ctrLoanContMetaData = yedApplyCtrLoanCtr.getCtrLoanContMetaData(nlsCreditInfoVO, sOrgVO, nlsApplyInfoVO);
                YedContResult yedContResult = null;
                try{
                    yedContResult = yedContService.signature(nlsApplyInfoVO.getApplySeq(), axquserid, "yed_dkcont.pdf", "个人借款合同", ctrLoanContMetaData);
                }catch (Exception e){
                    logger.error("合同签订异常，用信流水号"+nlsApplyInfoVO.getApplySeq()+"-错误信息为"+yedContResult.getMsg());
                    flag = true;
                    msg = "合同签订异常";
                    throw new OcmSystemException(yedContResult.getMsg());
                }
                if (!yedContResult.isRetFlag()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("【优e贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同签订出现异常，异常信息为" + yedContResult.getMsg());
                        flag = true;
                        msg = "合同签订出现异常";
                    }
                    throw new OcmSystemException(yedContResult.getMsg());
                }
                insertCfcaSignInfo(nlsCreditInfoVO, yedContResult, ConsoleConstant.CONT_TYPE_02, applySeq, cfcaSignInfoVO, signContractBean, nlsApplyInfoVO);
                updateCtrContInfo(applySeq, ConsoleConstant.CONT_TYPE_02,nlsApplyInfoVO.getLmtApplySeq());
            } else {
                CfcaSignInfoVO selectCfcaSignInfo = cfcaSignInfoService.queryByPk(cfcaSignInfoVO);
                if (selectCfcaSignInfo == null) {
                    int result = cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
                    if (result < 0) {
                        if (logger.isErrorEnabled()) {
                            logger.error("【优e贷合同签订服务】重跑时 插入CFCA信息表出错！ 用信申请流水号为:" + nlsApplyInfoVO.getApplySeq());
                            flag = true;
                            msg = "插入CFCA信息表出错";
                        }
                        throw new OcmSystemException("【优e贷合同签订服务】重跑时 插入CFCA信息表出错！");
                    }
                }
            }
            cfcaSignInfoVO = signContractBean.getCfcaSignInfoVO();
            // 调用cfca合同下载接口 todo 下载失败轮询3次，仍失败，记录失败信息
            if (StringUtil.isEmpty(signContractBean.getFilePath()) &&
                    StringUtils.isNotEmpty(cfcaSignInfoVO.getCfcaContNo()) &&
                    ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname().equals(cfcaSignInfoVO.getCfcaSignState())) {
                YedContResult yedContResult = null;
                try{
                    yedContResult = yedContService.downSignFile(nlsApplyInfoVO.getApplySeq(), cfcaSignInfoVO.getCfcaContNo(), nlsApplyInfoVO.getApplySeq() + "_yed_dkcont.pdf");
                }catch(Exception e){
                    logger.error("合同下载失败"+applySeq+"-异常信息为"+yedContResult.getMsg());
                    flag = true;
                    msg = "合同下载失败";
                    throw new OcmSystemException(yedContResult.getMsg());
                }

                if (!yedContResult.isRetFlag()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("【优e贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同下载出现异常，异常信息为" + yedContResult.getMsg());
                        flag = true;
                        msg = "合同下载异常";
                        throw new OcmSystemException("优e贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同下载出现异常，异常信息为" + yedContResult.getMsg());
                    }
                }
                signContractBean.setFilePath(yedContResult.getFileFullPath());
                insertCert(nlsApplyInfoVO, signContractBean);
                // 插入操作
                insertImageBizDetail(nlsApplyInfoVO, YedConstantSet.YED_YX_CONT_TYPE, FilenameUtils.getBaseName(yedContResult.getFileFullPath()),yedContResult.getFileFullPath());
            } else if (StringUtils.isNotEmpty(signContractBean.getFilePath())) {
                insertCert(nlsApplyInfoVO, signContractBean);
            }
            // 流程状态
            nlsApplyInfoVO.setFlowStatus(FLOW_STATUS_4);
            //放款插槽阶段
            nlsApplyInfoVO.setSoltStage(PrdAdaptedSoltEnums.PsdSoltStageEnum.REPAY.getVALUE());
            //更新过程表
            NlsProcessBizVO nlsProcessBizVO = new NlsProcessBizVO();
            nlsProcessBizVO.setApplySeq(nlsApplyInfoVO.getApplySeq());
            NlsProcessBizVO nlsProcessBizVO1 = nlsProcessBizService.queryByPk(nlsProcessBizVO);
            nlsProcessBizVO1.setSoltName2(nlsApplyInfoVO.getSoltName());
            nlsProcessBizVO1.setSoltState2(PrdAdaptedSoltEnums.SoltProcessStateEnum.SUCCESS.getCode());
            nlsProcessBizVO1.setSoltTime2(DateUtility.getCurrAppDateTimeString());
            //nlsProcessBizService.updateByPk(nlsProcessBizVo);
            nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
            nlsProcessBizService.updateByPk(nlsProcessBizVO1);
            producerService.sendMsg(new Message(TopicEnums.YEDLOANRELEASE_QUEUE_TASK_TOPIC.getTopicId(), TagEnums.YEDLOANRELEASE_QUEUE_TASK.getTagId(), nlsApplyInfoVO.getApplySeq(),
                    JSON.toJSONString(nlsApplyInfoVO).getBytes("UTF-8")));
        } catch (Exception e) {
            logger.error(Arrays.toString(e.getStackTrace()));
            nlsProcessBizVo.setExceptionFlag(true);
            nlsProcessBizVo.setExceptionMsg(new OcmSystemException(e));

        } finally {
            //合同校验必要参数失败，或者签订3次失败或者下载3次失败，将放款置为失败，过程置为失败06
            if(flag){
                logger.info("用信流水号为"+applySeq+"合同校验必要参数失败，或者签订3次失败或者下载3次失败");
                nlsApplyInfoVO.setNlsApplyState(BaseConstant.NLS_APPLY_STATE_03);
                nlsApplyInfoVO.setRefuseCause(msg);
                nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
                NlsProcessBizVO nlsProcessBizVO = new NlsProcessBizVO();
                nlsProcessBizVO.setApplySeq(nlsApplyInfoVO.getApplySeq());
                NlsProcessBizVO nlsProcessBizVO1 = nlsProcessBizService.queryByPk(nlsProcessBizVO);
                nlsProcessBizVO1.setSoltName2(nlsApplyInfoVO.getSoltName());
                nlsProcessBizVO1.setSoltState2(PrdAdaptedSoltEnums.SoltProcessStateEnum.FAILURE.getCode());
                nlsProcessBizVO1.setSoltTime2(DateUtility.getCurrAppDateTimeString());
                nlsProcessBizService.updateByPk(nlsProcessBizVO1);
            }
            logger.info("======>合同签订服务结束,流水号" + applySeq + "<======");
        }
    }


    private void insertCert(NlsApplyInfoVO nlsApplyInfoVO, SignContractBean signContractBean) throws OcmSystemException {
        //int result = yedUploadService.insertByFileUrl(signContractBean.getFilePath());
        int result = insertUploadRecord(nlsApplyInfoVO,signContractBean.getFilePath());
        if (result != 1) {
            if (logger.isErrorEnabled()) {
                logger.error("【优e贷合同签订服务】重跑时 插入上传信息表出错！ 用信申请流水号为:" + nlsApplyInfoVO.getApplySeq());
            }
            throw new OcmSystemException("【优e贷合同签订服务】重跑时 插入上传信息表出错！");
        }
    }

    public Integer insertUploadRecord(NlsApplyInfoVO nlsApplyInfoVO, String fpath){
        YedUploadRecordVO yedUploadRecordVO = new YedUploadRecordVO();
        yedUploadRecordVO.setApplSeq(nlsApplyInfoVO.getApplySeq());//用信流水号
        yedUploadRecordVO.setCreateTime(new Date());
        yedUploadRecordVO.setDealType("2");//处理阶段（1-授信 2-用信 3-借据）
        yedUploadRecordVO.setFileType("Y02");//Y01-授权书 Y02-借款合同 Y03-征信报告
        yedUploadRecordVO.setFileUrl(fpath);
        yedUploadRecordVO.setPrdId(nlsApplyInfoVO.getPrdId());
        yedUploadRecordVO.setUpErrMsg("");
        yedUploadRecordVO.setRecordId(UUID.randomUUID().toString().replace("-",""));
        yedUploadRecordVO.setUpNum(0);
        yedUploadRecordVO.setUpSta(0);
        yedUploadRecordVO.setUpTime(new Date());
        return yedUploadService.insert(yedUploadRecordVO);
    }

    /**
     * 根据客户ID获取客户信息
     */
    private CusIndivVO getCustInfo(String cusId) throws OcmSystemException {
        CusIndivVO cusIndivVO = new CusIndivVO();
        cusIndivVO.setCusId(cusId);
        cusIndivVO = cusIndivService.queryByPk(cusIndivVO);
        if (Objects.isNull(cusIndivVO)) {
            throw new OcmSystemException("根据客户号：" + cusId + "，查询到的客户信息为空！");
        }
        return cusIndivVO;
    }


    /**
     * 通过用信申请流水号、合同类型获取合同号
     */
    private String getContNo(String applySeq, String contType) throws OcmSystemException {
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        ctrLoanContVO.setSerno(applySeq);
        ctrLoanContVO.setContType(contType);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        if (Objects.isNull(ctrLoanContVO)) {
            logger.error("优e贷【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
            throw new OcmSystemException("优e贷用信申请【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
        }
        String ctrContNo = ctrLoanContVO.getContNo();
        if (StringUtil.isNullorBank(ctrContNo)) {
            logger.error("优e贷【合同签订服务】通过用信申请流水号、合同类型查询合同信息，得到的合同号为空！");
            throw new OcmSystemException("优e贷用信申请【合同签订服务】通过用信申请流水号、合同类型查询合同信息，得到的合同号为空！");
        }
        return ctrContNo;

    }

    /**
     * 保存合同签章记录
     *
     * @throws OcmSystemException
     * @author qiuyf
     * @version 0.1 初始为0.1,后续变更则修改
     * @since 2019年4月26日 上午10:53:53
     */
    private void insertCfcaSignInfo(NlsCreditInfoVO nlsCreditInfoVO, YedContResult yedContResult, String contType, String applySeq, CfcaSignInfoVO cfcaSignInfoVO, SignContractBean signContractBean, NlsApplyInfoVO nlsApplyInfoVO) throws OcmSystemException {
        String contNo = this.getContNo(applySeq, contType);
        if (logger.isInfoEnabled()) {
            logger.info("======>优e贷用信申请【合同签订服务】保存合同签章记录信息开始<===== 用信申请流水号为：" + applySeq + " 合同号为：" + contNo);
        }
        cfcaSignInfoVO = Optional.ofNullable(cfcaSignInfoVO).orElse(new CfcaSignInfoVO());
        //申请流水号
        cfcaSignInfoVO.setApplySeq(applySeq);
        //产品id
        cfcaSignInfoVO.setPrdId(nlsCreditInfoVO.getPrdId());
        //产品代码
        cfcaSignInfoVO.setPrdCode(nlsCreditInfoVO.getPrdCode());
        //产品名称
        cfcaSignInfoVO.setPrdName(nlsCreditInfoVO.getPrdName());
        //合同号
        cfcaSignInfoVO.setContNo(contNo);
        //安心签合同号
        cfcaSignInfoVO.setCfcaContNo(yedContResult.getAxqContNo());
        //客户号
        cfcaSignInfoVO.setCusId(nlsCreditInfoVO.getCusId());
        //客户名称
        cfcaSignInfoVO.setCusName(nlsCreditInfoVO.getCusName());
        //渠道号
        cfcaSignInfoVO.setPrdType(nlsCreditInfoVO.getChannelNo());
        // 网贷经办机构
        cfcaSignInfoVO.setNlsOperOrgid(nlsCreditInfoVO.getNlsOperOrgid());
        // 网贷经办人
        cfcaSignInfoVO.setNlsOperUserid(nlsCreditInfoVO.getNlsOperUserid());
        // 账务机构
        cfcaSignInfoVO.setFinaBrId(nlsCreditInfoVO.getNlsOperOrgid());
        //cfca签署状态 = “未签署”
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        signContractBean.setCfcaSignInfoVO(cfcaSignInfoVO);
        nlsApplyInfoVO.setSignContractBean(signContractBean);
        cfcaSignInfoVO.setCfcaSignTime(yedContResult.getAxqSignTime());
        int num = cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
        if (num < 0) {
            if (logger.isErrorEnabled()) {
                logger.error("优e贷用信申请【合同签订服务】用信申请流水号为: " + applySeq + "合同号为：" + contNo + " 往cfca加签信息表新增数据出错!");
            }
            throw new OcmSystemException("优e贷用信申请【合同签订服务】用信申请流水号为: " + applySeq + "合同号为：" + contNo + " 往cfca加签信息表新增数据出错!");
        }
        if (logger.isInfoEnabled()) {
            logger.info("======>优e贷用信申请【合同签订服务】保存合同签章记录信息结束<===== 用信申请流水号为：" + applySeq + " 合同号为：" + contNo);
        }
    }

    /**
     * 签章接口
     */
    //private void execute3207(NlsCreditInfoVO nlsCreditInfoVO, String cfcaContNo, String contType, String applySeq, SignContractBean signContractBean, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
    //    logger.info("======> 【优e贷用信申请合同签订服务】调用cfca关键字签署接口【3207】，合同签章开始<====== 用信申请流水号：" + applySeq);
    //
    //    ReqElectronicSignature3207Bean req3207Bean = new ReqElectronicSignature3207Bean();
    //
    //    ReqElectronicSignature3207Struct signCtrByKyd3207 = new ReqElectronicSignature3207Struct();
    //    //安心签合同号
    //    signCtrByKyd3207.setContractNo(cfcaContNo);
    //    //组装印章的位置确定信息--------------------- start
    //    ReqElecTronicSignature3207SignKeyWordInfo signKeyword = new ReqElecTronicSignature3207SignKeyWordInfo();
    //    // 关键字
    //    signKeyword.setKeyword(signKeyWord);
    //    // X轴偏移坐标
    //    signKeyword.setOffsetCoordX(xOfStcoordPosn);
    //    // Y轴偏移坐标
    //    signKeyword.setOffsetCoordY(yOfStcoordPosn);
    //    // 签章图片宽度
    //    signKeyword.setImageWidth(signImgWdth);
    //    // 签章图片高度
    //    signKeyword.setImageHeight(signImgHght);
    //    //组装印章的位置确定信息--------------------- end
    //    signCtrByKyd3207.setSignKeyword(signKeyword);
    //
    //    //组装印章的详细信息-------------------------------------------------------------------------------------------------start
    //    ReqElecTronicSignature3207SignSealInfo signSealInfo = new ReqElecTronicSignature3207SignSealInfo();
    //    /**
    //     * 根据配置主键、参数值，查参数配置表
    //     */
    //    SCfgParamVO sCfgParamVO = new SCfgParamVO();
    //    sCfgParamVO.setParamKey(ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue());
    //    sCfgParamVO = sCfgParamService.queryByCondition(sCfgParamVO);
    //    if (Objects.isNull(sCfgParamVO)) {
    //        if (logger.isErrorEnabled()){
    //            logger.error("【优e贷用信申请合同签订服务】 根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，无法获取机构cfca开户号初始化信息为空，请核查是否初始化数据表！");
    //        }
    //        throw new OcmSystemException("【优e贷用信申请合同签订服务】 根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，无法获取机构cfca开户号初始化信息为空，请核查是否初始化数据表！");
    //    } else {
    //        if (StringUtil.isNullorBank(sCfgParamVO.getParamValue())) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("【优e贷用信申请合同签订服务】根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，获取到的机构开户号为空，请核查是否初始化数据表！");
    //            }
    //            throw new OcmSystemException("【优e贷用信申请合同签订服务】根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，获取到的机构开户号为空，请核查是否初始化数据表！");
    //        }
    //    }
    //    // 用户ID（广州银行已在cfca开过户，该值是初始化在表中的）
    //    signSealInfo.setUserId(sCfgParamVO.getParamValue());
    //    // 授权时间
    //    signSealInfo.setAuthorizationTime(TimeUtil.getTimeStampByPattern("yyyyMMddHHmmss"));
    //    // 授权地点
    //    signSealInfo.setLocation(authaddr);
    //    // 项目编号
    //    signSealInfo.setProjectCode(UUIDUtil.getUUID());
    //    /** 是否检查项目编号 （0：不检查；1：检查；默认为0，需要校验项目编号的时候传送）*/
    //    // 签章图片 （需要根据业务数据的经办机构号，到本地路径 /home/xxx/下放置的银行开户影像信息，找到机构号对应的签章信息） 文件命名规范：xx银行签署图orgCode.xx，文件的结尾一定是银行唯一的机构号
    //    signSealInfo.setImageData(getImageDataStr(nlsCreditInfoVO.getNlsOperOrgid()));
    //
    //    /** 印章ID （添加印章返回的印章ID，不传时为默认印章）*/
    //    //组装印章的详细信息--------------------------------------------------------------------------------------------------------end
    //    signCtrByKyd3207.setSignSealInfo(signSealInfo);
    //
    //    req3207Bean.setSignContractByKeyword(signCtrByKyd3207);
    //
    //    RespElectronicSignature3207Bean resp3207Bean = new RespElectronicSignature3207Bean();
    //    try {
    //        //resp3207Bean = sedCfcaService.signSeal(req3207Bean);
    //        if (Objects.isNull(resp3207Bean)) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("调用cfca关键字签署接口【3207】，返回的签署信息为空，合同签署失败！ 用信申请流水号：" + nlsApplyInfoVO.getApplySeq());
    //            }
    //            throw new Exception("调用cfca关键字签署接口【3207】，返回的签署信息为空，合同签署失败！ 用信申请流水号：" + nlsApplyInfoVO.getApplySeq());
    //        }
    //    } catch (Exception e) {
    //        if (logger.isErrorEnabled()){
    //            logger.error("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "执行合同签订出现异常，异常信息为：" + e.getMessage());
    //        }
    //        throw new ExternalSysException("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "执行合同签订出现异常，异常信息为：" + e.getMessage());
    //    }
    //    signContractBean.getCfcaSignInfoVO().setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
    //    if (logger.isInfoEnabled()){
    //        logger.info("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "调用cfca关键字签署接口【3207】结束。返回结果为：" + JSON.toJSONString(resp3207Bean));
    //    }
    //    // 更新cfca加签信息
    //    updCfcaSignInfo(getContNo(applySeq, contType));
    //    // 更新合同信息
    //    updateCtrContInfo(applySeq, contType);
    //}

    /**
     * 更新合同信息
     */
    private void updateCtrContInfo(String applySeq, String contType,String lmtApplySeq) throws OcmSystemException {
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        ctrLoanContVO.setSerno(applySeq);
        ctrLoanContVO.setContType(contType);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        if (Objects.isNull(ctrLoanContVO)) {
            logger.error("优e贷【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
            throw new OcmSystemException("优e贷用信申请【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
        }

        //合同签订成功，检查合同表的推荐人工号和推荐人所属机构取值
        CusReferrerInfoVO referrerInfoVO = new CusReferrerInfoVO();
        referrerInfoVO.setLmtApplySeq(lmtApplySeq);
        referrerInfoVO = cusReferrerInfoService.queryChargeoffBrIdByPk(referrerInfoVO);
        if(!Objects.isNull(referrerInfoVO)){
            ctrLoanContVO.setPerformanceOwner(referrerInfoVO.getReferrerId());
            ctrLoanContVO.setPerformanceOrg(referrerInfoVO.getMainBrId());
            ctrLoanContVO.setFinaBrId(referrerInfoVO.getChargeOffBrId());
        }

        //合同状态 已签订
        ctrLoanContVO.setContState(CONT_STATUS_200);
        int result = ctrLoanContService.updateByPk(ctrLoanContVO);
        if (result != 1) {
            logger.error("优e贷【合同签订服务】通过用信申请流水号、合同类型更新合同信息为已签订出现异常！");
            throw new OcmSystemException("优e贷【合同签订服务】通过用信申请流水号、合同类型更新合同信息为已签订出现异常");
        }
    }


    /**
     * 通过机构号获取指定路径下的签章图片信息
     */
    //private String getImageDataStr(String orgCode) throws OcmSystemException {
    //    if (StringUtil.isNullorBank(orgCode)) {
    //        throw new OcmSystemException("授信申请经办机构号为空，无法获取指定路径下的签章图片信息！");
    //    }
    //    String imageData = null;
    //    //获取指定路径下的文件信息
    //    File[] files = new File(imagesAddr).listFiles();
    //    if (null == files || files.length == 0) {
    //        throw new OcmSystemException("路径【：" + imagesAddr + "】，不存在相关的文件信息，请核查!");
    //    }
    //    for (int i = 0; i < files.length; i++) {
    //        if (files[i].isDirectory()) {
    //            continue;
    //        }
    //        //获取文件名称
    //        String fileName = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
    //        if (fileName.endsWith(orgCode)) {
    //            try {
    //                imageData = Base64.encodeBytes(FileUtil.toByteArray(files[i]));
    //            } catch (IOException e) {
    //                logger.error("处理cfca关键字签署接口【3207】，签章图片处理失败！", e);
    //                throw new OcmSystemException("签章图片处理异常，调用cfca关键字签署接口【3207】失败！");
    //            }
    //        }
    //    }
    //    if (StringUtil.isNullorBank(imageData)) {
    //        throw new OcmSystemException("在路径【：" + imagesAddr + "】下，找不到机构标识为【" + orgCode + "】的签章图片信息，请核查！");
    //    }
    //    return imageData;
    //}

    /**
     * 更新cfca加签信息签署状态为“已签署”
     */
    private void updCfcaSignInfo(String contNo) throws OcmSystemException {
        CfcaSignInfoVO cfcaSignInfoVO = new CfcaSignInfoVO();
        cfcaSignInfoVO.setContNo(contNo);
        cfcaSignInfoVO = cfcaSignInfoService.queryByPk(cfcaSignInfoVO);
        if (Objects.isNull(cfcaSignInfoVO)) {
            if (logger.isErrorEnabled()) {
                logger.error("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，查询到的cfca加签信息为空！");
            }
            throw new OcmSystemException("根据合同号【" + contNo + "】，查询到的cfca加签信息为空！");
        }
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        int result = cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
        if (result != 1) {
            if (logger.isErrorEnabled()) {
                logger.error("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，更新cfca加签信息失败！");
            }
            throw new OcmSystemException("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，更新cfca加签信息失败");

        }
    }

    /**
     * 获取机构信息
     */
    private SOrgVO getSOrg(String orgCode) throws OcmSystemException {
        SOrgVO sOrgVO = new SOrgVO();
        sOrgVO.setOrgCode(orgCode);
        sOrgVO = sOrgService.queryByPk(sOrgVO);
        if (Objects.isNull(sOrgVO)) {
            throw new OcmSystemException("通过机构号【" + orgCode + "】，获取到机构信息为空！");
        }
        return sOrgVO;
    }

    /**
     * 获取额度协议信息
     */
    private LmtPrdContVO getLmtPrdCont(String lmtApplySeq) throws OcmSystemException {
        LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(lmtApplySeq);
        if (Objects.isNull(lmtPrdContVO)) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信协议信息为空！");
        }
        if (null == lmtPrdContVO.getLmtAmt()) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信额度为空！");
        }
        return lmtPrdContVO;
    }

    /**
     * 根据日期与日期单位获取数值
     */
    private String getDateString(String date, String dateType) throws OcmSystemException {
        if (!Flag) {
            try {
                MessageRuleCheckUtil.checkDate("授信有效日期", date, "yyyy-MM-dd");
                Flag = true;
            } catch (BizException e) {
                throw new OcmSystemException("组装合同参数时，校验到授信协议信息表的有效日期不符合格式“yyyy-MM-dd”");
            }
        }
        String result = "";
        String[] dates = date.split("-");
        if (TimeType.YEAR.getKey().equals(dateType)) {
            result = dates[0];
        } else if (TimeType.MONTH.getKey().equals(dateType)) {
            result = dates[1];
        } else if (TimeType.DAY.getKey().equals(dateType)) {
            result = dates[2];
        }
        return result;
    }

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;


    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("yedUploadService")
    private YedUploadService yedUploadService;

    @Autowired
    @Qualifier("sOrgService")
    private SOrgService sOrgService;

    @Autowired
    private YedApplyCtrLoanCtr yedApplyCtrLoanCtr;

    @Autowired
    private YedContService yedContService;

    @Autowired
    private ImageBizDetailService imageBizDetailService;

    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;
    @Autowired
    private CusReferrerInfoService cusReferrerInfoService;

    @Autowired
    @Qualifier("nlsProcessBizService")
    private NlsProcessBizService nlsProcessBizService;

    /**
     * 插入记录到影响明细表
     * @param
     * @param imgType
     * @param fileName
     * @param filePath
     */
    private void insertImageBizDetail(NlsApplyInfoVO nlsApplyInfoVO, String imgType, String fileName, String filePath) {
        ImageBizDetailVO imageBizDetail = new ImageBizDetailVO();
        imageBizDetail.setApplySeq(nlsApplyInfoVO.getApplySeq());
        imageBizDetail.setBizStage("用信合同");
        imageBizDetail.setFileDesc("优e贷用信合同");
        imageBizDetail.setFileName(fileName);
        imageBizDetail.setFilePath(filePath);
        imageBizDetail.setImageId(imgType);
        imageBizDetail.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizDetail.setImageType(imgType);
        imageBizDetailService.insertImageBizDetail(imageBizDetail);
    }

    /**
     * 查询推荐人工号表获取出账机构
     * @param nlsCreditInfoVO
     * @return
     */
    public String getRefferOrgId(NlsCreditInfoVO nlsCreditInfoVO) throws OcmSystemException{
        CusReferrerInfoVO cusReferrerInfoVO = new CusReferrerInfoVO();
        cusReferrerInfoVO.setLmtApplySeq(nlsCreditInfoVO.getLmtApplySeq());
        cusReferrerInfoVO = cusReferrerInfoService.queryChargeoffBrIdByPk(cusReferrerInfoVO);

        if (Objects.isNull(cusReferrerInfoVO)) {
            throw new OcmSystemException("通过授信申请流水号【" + nlsCreditInfoVO.getLmtApplySeq() + "】，获取到推荐人信息为空！");
        }

        return cusReferrerInfoVO.getChargeOffBrId();
    }

    @Override
    public void run() {
        try {
            doExecute(new NlsProcessBizVO(),nlsApplyInfoVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
